let cmm = (() => {
	let that = {};
	// let ws = new WebSocket("ws:/localhost:3000");
	let ws = new WebSocket("ws://192.168.2.14:3000");
	// 储存回调函数的容器
	let callBackMap = {};
	// 回调函数的名字
	let callBackIndex = 1;

	// 监听信息
	ws.onmessage = (msg) => {
		let pak = JSON.parse(msg.data);
		console.log(pak);
		if (pak.isGuangbo) {
			// 根据广播的是什么去做对应的逻辑
			cc.vv.ServerCallBack[pak.type](pak.data);
		} else {
			let index = pak.callBackIndex;
			if (index) {
				let cb = callBackMap[index];
				// 如果这条信息有对应的回调函数，执行函数
				if (pak.data.err) {
					cb(pak.data.err);
				} else {
					cb(null, pak.data.info);
				}
			}
		}
	};
	// 发信息
	let transmit = (type, data, callBackIndex) => {
		let msg = { type: type, data: data, callBackIndex: callBackIndex };
		ws.send(JSON.stringify(msg));
	};

	let serialize = (type, data, cb) => {
		// 回调函数需要保存下来
		callBackMap[callBackIndex] = cb;
		transmit(type, data, callBackIndex);
		callBackIndex++;
	};
	// 请求注册
	that.request_register = function (data, cb) {
		serialize(cc.vv.communicateEvent.REGISTER, data, cb);
	};

	// 请求登录
	that.request_login = function (data, cb) {
		serialize(cc.vv.communicateEvent.LOGIN, data, cb);
	};

	// 请求进入房间
	that.request_enterRoom = function (data, cb) {
		serialize(cc.vv.communicateEvent.ENTERROOM, data, cb);
	};
	// 请求房间房间信息
	that.request_roomMsg = function (data, cb) {
		serialize(cc.vv.communicateEvent.ENTERROOM, data, cb);
	};
	// 开始游戏
	that.request_startGame = function (data, cb) {
		serialize(cc.vv.communicateEvent.STARTGAME, data, cb);
	};
	// 请求落子
	that.request_moveChess = function (data, cb) {
		serialize(cc.vv.communicateEvent.MOVECHESS, data, cb);
	};


	return that;
})();
module.exports = cmm;
